<style lang="less">
.upload-image {
  .is-disabled ~ .el-upload--picture-card{
    display: none;
  }
  .el-upload--picture-card{
    background: transparent;
    .el-icon-plus{
      color: #fff;
    }

  }
}

</style>
<template>
  <div class="comp-new">
    <el-form ref="newForm" :model="newForm" :label-width="150+'px'">
      <p>一次性上传图片数量最多20张</p>
      <br>
        <el-upload
            class="upload-image"
            :action="config.uploadsPicture"
            :data="param"
            list-type="picture-card"
            :file-list="fileList"
            accept="image/*"
            :multiple="true"
            :limit="20"
            :on-success="handleUploadSuccess"
            :disabled="!hasPermission('029012')">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="hasPermission('029013')"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
        </el-upload>

    </el-form>
    <!-- 定位 start -->
    <el-dialog v-if="locationModalVisible" :visible.sync="locationModalVisible" width="800px" :close-on-click-modal="false" :close-on-press-escape="false" destroy-on-close append-to-body>
      <h2 slot="title" class="fs-18">定位 <small>（点击地图选点）</small></h2>
      <Location
          ref="location"
          :coord="coord"
          type="equipment"
          @save="saveLocation"
          @cancel="locationModalVisible=false"
      >
      </Location>
    </el-dialog>
    <!-- 定位 end -->
    <el-dialog :visible.sync="previewVisible" v-if="previewVisible" append-to-body>
      <img style="max-width: 100%" :src="previewImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import Location from '@/components/census/record/Location.vue'
export default {
  name: 'newEquipment',
  components: {
    Location
  },
  props: {
    id: {
      type: String,
      default: "",
    },
    activeData: {
      type: Object,
      default(){
        return null
      },
    },
    unit: {
      type: Object,
      default(){
        return {}
      },
    },
    type: {
      type: String,
      default: 'pool'
    }
  },
  computed: {
    ...mapState(["siteInfos"]),
    coord () {
      if(this.newForm.lon){
        return this.newForm.lon + ',' + this.newForm.lat
      }
    },
  },
  watch: {
    activeData () {
      this.initForm()
    },
    fileList (fileList) {
      let urls = fileList.map(item=>item.url)
      this.newForm.img = urls.join(',')
    }
  },
  data () {
    return {
      newForm: {},
      loading: false,
      typeList:[],
      productList: [],
      locationModalVisible: false,
      fileList: [],
      previewImageUrl: '',
      previewVisible: false,
      param:{'businessId':this.id,token: this.siteInfos.token},
      loading: false
    }
  },
  methods: {
    initForm () {
      this.fileList = []
      this.loading = true
      this.$get('/business/picture/pictureList',{businessId:this.id}).then(res => {
        this.loading = true
        let imgList = res.data.map((item,index) => {
          return {
            name: 'file'+index,
            url: item.filePath
          }
        })
        this.fileList = imgList
      }, (err) =>{
        this.loading = true
      })
      // if(this.activeData){
      //   this.newForm = this.utils.pick(this.activeData,['id','businessId','businessName','deviceClassify','img','lon','lat','name','number','position','internetofthingsCardnum','transDeviceCode','deviceType','installtime','productId','spec','alarmPhone','installperson','installpersonPhone','remark'])
      //   let imgList = this.activeData.imgList.map((item,index) => {
      //     return {
      //       name: 'file'+index,
      //       url: item
      //     }
      //   })
      //   this.fileList = imgList
      // }else{
      //   this.newForm = {
      //     businessId: this.unit.id,
      //     businessName: this.unit.name,
      //     deviceClassify: this.type,
      //     img: '',
      //     lon: '',
      //     lat: ''
      //   }
      //   if(this.$refs['newForm']){
      //     this.$refs['newForm'].resetFields()
      //   }
      // }
    },
    getType () {
      this.$get('/fireFightingIOT/device/deviceTypeList',{type:this.type}).then(res => {
        this.typeList = res.data
      }, (err) =>{
        if(err.msg){
          this.$message.error(err.msg);
        }
      })
    },
    getProduct () {
      this.$get('/fireFightingIOT/device/productList',{type:this.type}).then(res => {
        this.productList = res.data
      }, (err) =>{
        if(err.msg){
          this.$message.error(err.msg);
        }
      })
    },
    locateAction () {
      this.locationModalVisible = true
    },
    saveLocation (coord) {
      this.newForm.lon = coord[0]
      this.newForm.lat = coord[1]
      this.locationModalVisible = false
    },
    handlePictureCardPreview (file) {
      this.previewImageUrl = file.url;
      this.previewVisible = true;
    },
    handleUploadSuccess (res, file) {
      // console.log("file", file);
      // console.log("fileUid", file.uid);
      this.fileList.push({name: res.data.fileName,url:res.data.filePath})
      // this.fileList = []
      // this.initForm()
    },
    handleRemove (file) {
      // console.log(file.url,this.id)
      // console.log(file, fileList);
      let filePath = file.url;
      let id = this.id;
      let params = Object.assign({filePath:filePath, businessId: id});
      let url = "/business/picture/delete";
      this.$ajax({
        url: url,
        method: 'post',
        data: params
      }).then( data => {
        this.initForm()
      }, error => {
        this.$message.error(error.msg)
      })

    },
    submitAction () {
      this.$refs['newForm'].validate((valid) => {
        if (valid) {
          this.$emit('submitting')
          this.loading = true
          let params = Object.assign({deviceClassify: this.type},this.newForm)
          let url = !params.id ? '/fireFightingIOT/device/typeAdd' : '/fireFightingIOT/device/typeUpdate'
          this.$ajax({
            url: url,
            method: 'post',
            data: params
          }).then( data => {
            this.loading = false
            this.$message.success('保存成功')
            this.$emit('success',data);
          }, error => {
            this.loading = false
            this.$message.error(error.msg);
            this.$emit('fail');
          })
        } else {
          return false;
        }
      });
    },
    cancelAction () {
      this.$emit('cancel');
    }
    // ,
    // onChange(res, file){
    //   this.fileList.push({name: res.data.fileName,url:res.data.filePath})
    //   console.log({name: res.data.fileName,url:res.data.filePath})
    //   console.log("fileList",res)
    // }
    // resetForm () {
    // 	this.newForm = {}
    // 	this.$refs['newForm'].resetFields()
    // }
  },
  created () {
    this.getType()
    this.getProduct()
    this.initForm()
    //this.fileList = [{url:'https://xf.wisdiot.com/uploads/20210317/1615944908469.png'},{url:'https://xf.wisdiot.com/uploads/20210317/1615944908469.png'}]
  },
}
</script>